import Vue from 'vue'
import VueRouter from 'vue-router'
import Layout from '../views/Layout.vue'
import Login from '../views/Login.vue'
import Register from '../views/Register.vue'
import Article from '../views/Article.vue'
import Collect from '../views/Collect.vue'
import Like from '../views/Like.vue'
import User from '../views/User.vue'
import Detail from '../views/Detail.vue'

Vue.use(VueRouter)

const routes = [{
        path: '/',
        redirect: '/article', //跳转到首页
        component: Layout,
        children: [{
                path: '/article',
                component: Article,
            },
            {
                path: '/collect',
                component: Collect,
            },
            {
                path: '/like',
                component: Like,
            },
            {
                path: '/user',
                component: User,
            },

        ]
    },
    {
        path: '/login',
        component: Login
    },
    {
        path: '/register',
        component: Register
    }, {
        path: '/detail/:id',
        component: Detail
    }
]

const router = new VueRouter({
    routes
})

//导航守卫来决定路由是否放行

//1.当访问非登录和注册页面时，需要验证token
//2.当访问白名单页面（登录注册等页面）时，不需要验证token

import { getToken } from '@/utils/storage'
const whiteList = ['/login', '/register']
router.beforeEach((to, from, next) => {
    const token = getToken()
    if (token) {
        //如果存在token则放行
        next()
    } else {
        //判断是否为白名单页面
        if (whiteList.includes(to.path)) {
            next()
        } else {
            next('/login')
        }
    }

})




export default router